package leetcode.数组;

import java.util.*;

/**
 * 插入区间
 */
public class Test57插入区间 {

    static class Interval {
        int start;
        int end;

        Interval() {
            start = 0;
            end = 0;
        }

        Interval(int s, int e) {
            start = s;
            end = e;
        }

        @Override
        public String toString() {
            return "[" + start + "," + end + "]";
        }
    }

    public static List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        if (intervals == null || intervals.size() == 0) {
            intervals.add(newInterval);
            return intervals;
        }
        if (intervals.size() == 1 && newInterval == null) {
            return intervals;
        }
        // 先插进去，然后排序、合并重叠区间
        intervals.add(newInterval);
        int n = intervals.size();
        int[] starts = new int[n];
        int[] ends = new int[n];
        for (int i = 0; i < n; i++) {
            starts[i] = intervals.get(i).start;
            ends[i] = intervals.get(i).end;
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        int i = 0;
        List<Interval> res = new ArrayList<>();
        while (i < n) {
            int st = starts[i];
            // 排序后，找到开始点 > 结束点 的 i，然后重新组织区间
            while (i < n - 1 && starts[i + 1] <= ends[i])
                i++;
            int en = ends[i];
            res.add(new Interval(st, en));
            i++;
        }
        return res;
    }

    public static int[][] insert(int[][] intervals, int[] newInterval) {
        if (newInterval.length == 0)
            return intervals;
        int[][] new_intervals = new int[intervals.length + 1][2];
        System.arraycopy(intervals, 0, new_intervals, 0, intervals.length);
        new_intervals[intervals.length] = newInterval;
        Arrays.sort(new_intervals, (x, y) -> x[0] - y[0]);
        List<int[]> ans = new ArrayList<>();
        ans.add(new_intervals[0]);
        for (int i = 1; i < new_intervals.length; i++) {
            int[] cur = new_intervals[i];
            int[] last = ans.get(ans.size() - 1);
            if (cur[0] <= last[1]) {
                last[1] = Math.max(last[1], cur[1]);
                ans.remove(ans.size() - 1);
                ans.add(last);
            } else {
                ans.add(cur);
            }
        }

        return ans.toArray(new int[ans.size()][2]);
    }

    public static void main(String[] args) {
//        Interval i1 = new Interval(1, 3);
//        Interval i2 = new Interval(6, 9);
//        List<Interval> intervals = new ArrayList<>();
//        intervals.add(i1);
//        intervals.add(i2);
//        Interval interval = new Interval(2, 5);
//        System.out.println(insert(intervals, interval));


    }

}
